package NetWork;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpClient {

    public DatagramSocket socket = null;
    public String serverIp=null;
    public int serverPort ;
    public UdpClient(String serverIp,int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp=serverIp;
        this.serverPort=serverPort;
    }

    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner sc=new Scanner(System.in);
        while(true){

            System.out.println("->");
            String request=sc.next();

            DatagramPacket datagramPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            //这里的IP传入的时候需要改变，点分十进制127.0.0.1，每个部分都是0-255一个字节
            socket.send(datagramPacket);
            DatagramPacket getRelay = new DatagramPacket(new byte[4096],4096);
            socket.receive(getRelay);
            String response = new String(getRelay.getData(),0,getRelay.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
             UdpClient udpClient = new UdpClient("127.0.0.1",9090);
             udpClient.start();
    }
}
